package WebAll.pojo;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;

import java.util.List;

/**
 * @author ：Yan Guang
 * @date ：Created in 2020/5/30 20:21
 * @description：
 */
public class Dom4jTest {
    @Test
    public void test1(){
        //声明一个输入流，来读入我们的xml文件
        try {
            SAXReader saxReader = new SAXReader();
            //读入
            Document read = saxReader.read("src/books.xml");
            System.out.println(read);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }
    @Test
    public void test2() throws Exception{
        //1读取books.xmL文件
        SAXReader saxReader = new SAXReader();
        //2通过Document 对象获取根元素
        Document document = saxReader.read("src/books.xml");
        //3通过根元素获取book标签对象
        Element rootElement = document.getRootElement();
        List<Element> booklist = rootElement.elements("book");
        //4遍历，处理每个book标签转换为Book类
        for (Element book :booklist) {
            Element elementname = book.element("name");
            String name = elementname.getText();
            Element elementprice = book.element("price");
            String price = elementprice.getText();
            Element elementauthor = book.element("author");
            String author = elementauthor.getText();
            //获取我们的sn，通过获取对象的值这个方法
            String snvalue = book.attributeValue("sn");
            //把pirce解析成Double类型
            System.out.println(new book(snvalue,name,Double.parseDouble(price),author));
        }


    }
}
